#include "zonemanager.h"

namespace fireplane
{


	ZoneManager::ZoneManager()
	{

	}

	ZoneManager::~ZoneManager()
	{

	}

	void ZoneManager::init( float mapHeight,float zoneHeight )
	{
		int zoneCount = (int)(mapHeight / zoneHeight) + 1;
		
		for (int i = 0;i < zoneCount;i++)
		{
			list<Object*> zone;
			_all_zones.push_back(zone);
		}

		_mapHeight = mapHeight;
		_zoneHeight = zoneHeight;
	}

	int ZoneManager::checkZone( float posY )
	{
		if (posY <= 0)
		{
			return 0;
		}

		unsigned int idx = (int)(posY / _zoneHeight);
		if (idx >= _all_zones.size())
		{
			idx = _all_zones.size() - 1;
		}

		return idx;
	}

	void ZoneManager::removeObject(unsigned int idx,Object* object)
	{
		bool find = false;
		if (idx >= 0 && idx < _all_zones.size())
		{
			list<Object*>& objectList = _all_zones[idx];
			list<Object*>::iterator it = objectList.begin();
			for (;it != objectList.end();it++)
			{
				if (object == *it)
				{
					objectList.erase(it);
					find = true;
					break;
				}
			}
		}
		
		if (!find)
		{
			for (unsigned int i = 0;i < _all_zones.size();i++)
			{
				list<Object*>& objectList = _all_zones[i];
				list<Object*>::iterator it = objectList.begin();
				for (;it != objectList.end();it++)
				{
					if (object == *it)
					{
						objectList.erase(it);
						return;
					}
				}
			}
		}
	}

	void ZoneManager::moveObject( Object* object,
		unsigned int lastIdx,unsigned int newIdx )
	{
		if (lastIdx >= 0 && lastIdx < _all_zones.size())
		{
			list<Object*>& objectList = _all_zones[lastIdx];
			list<Object*>::iterator it = objectList.begin();
			for (;it != objectList.end();it++)
			{
				if (object == *it)
				{
					objectList.erase(it);
					break;
				}
			}
		}

		if (newIdx >= 0 && newIdx < _all_zones.size())
		{
			_all_zones[newIdx].push_back(object);
		}
		else
		{
			if (newIdx < 0)
			{
				_all_zones[0].push_back(object);
			}
			else
			{
				_all_zones[_all_zones.size() - 1].push_back(object);
			}
		}
	}

}